package com.hp.test.concurrent.producer_consumer.pc1;

import lombok.Getter;
import lombok.Setter;

import java.util.LinkedList;
import java.util.Random;

/**
 * 用wait和notify实现生产者消费者
 *
 * @author hupan
 * @date 2021-05-03 14:10
 */
public class ProducerAndConsumer1 {

    public static void main(String[] args) {
        Storage storage = new Storage();
        Producer producer = new Producer("生产者", storage);
        Consumer consumer = new Consumer("消费者", storage);

        new Thread(producer).start();
        new Thread(consumer).start();
    }

}


class Storage {
    /**
     * 仓库最大存储量
     */
    private final int MAX_SIZE = 5;
    private final Random random = new Random();
    /**
     * 仓库存储的载体
     */
    private final LinkedList<Integer> list = new LinkedList<>();

    // 生产产品
    public synchronized void produce(String producer) {
        // 如果仓库已满
        while (list.size() == MAX_SIZE) {
            System.out.println("仓库已满，【" + producer + "】： 暂时不能执行生产任务!");
            try {
                // 由于条件不满足，生产阻塞
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 生产产品
        int data = random.nextInt(100);
        list.add(data);
        System.out.println("【" + producer + "】：生产了" + data + "【现仓储量为】:" + list.size());
        notifyAll();
    }

    // 消费产品
    public synchronized void consume(String consumer) {
        //如果仓库存储量不足
        while (list.size() == 0) {
            System.out.println("仓库已空，【" + consumer + "】： 暂时不能执行消费任务!");
            try {
                // 由于条件不满足，消费阻塞
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        int data = list.remove();
        System.out.println("【" + consumer + "】：消费了" + data + "【现仓储量为】:" + list.size());
        notifyAll();
    }

}


@Getter
@Setter
class Producer extends Thread {
    private String producer;
    private Storage storage;

    public Producer(String producer, Storage storage) {
        this.producer = producer;
        this.storage = storage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            storage.produce(producer);
        }
    }

}


@Getter
@Setter
class Consumer extends Thread {
    private String consumer;
    private Storage storage;

    public Consumer(String consumer, Storage storage) {
        this.consumer = consumer;
        this.storage = storage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            storage.consume(consumer);
        }
    }

}




